define(function (require, exports, module) {

    require("apps/grid");
    require("apps/file");
    require("apps/easyui");
    require("apps/boxselect");
    exports.init = function (ctx, uuid) {

        var _pageComponent = new $.PageDomFactory(uuid);

        var pageListComponent = new $.PageListComponent(uuid, {
            view: {
                grid: "user_table",
                myToolbar: "news_tb",
                colbar: "user_list_btn"
            },
            configs: {
                gridTitle: "用户列表",
                gridUrl: ctx + "/app/api/sysMember/conditionList",
                gridColumns: [
                    {
                        field: 'id',
                        checkbox: true
                    },
                    {
                        field: 'temp1',
                        hidden: true
                    },
                    {
                        field: 'userNumber',
                        title: '用户名',
                        width: 80,
                        align: 'left'
                    },
                    {
                        field: 'userName',
                        title: '姓名',
                        width: 50,
                        align: 'left'
                    },
                    {
                        field: 'userHead',
                        title: '头像',
                        width: 50,
                        align: 'left',
                        formatter: function (value, row, index) {
                            var v = ctx + "/print/upload/default/pic1.png";
                            if(value){
                                v = ctx + "/print/" + value;
                            }
                            return '<img data-id="userHead" src="'+ v + '" style="width: 36px;height: 36px;" >';
                        }
                    },
                    {
                        field: 'orgsDescription',
                        title: '小组',
                        width: 50,
                        align: 'left',
                        formatter: function (value, row, index) {
                            return value || "<a>N/A</a>";
                        }
                    },
                    {
                        field: 'email',
                        title: '邮箱',
                        width: 80,
                        align: 'left',
                        formatter: function (value, row, index) {
                            return !value ? "<a>N/A</a>" : value;
                        }
                    },
                    {
                        field: 'mobile',
                        title: '手机',
                        width: 60,
                        align: 'left',
                        formatter: function (value, row, index) {
                            return !value ? "<a>N/A</a>" : value;
                        }
                    },
                    {
                        field: 'available',
                        title: '状态',
                        width: 50,
                        align: 'left',
                        formatter: function (value, row, index) {
                            if (value == "1"
                                && value != null) {
                                return "启用";
                            } else {
                                return "禁用";
                            }
                        }
                    }
                ]
            },
            events: {
                renderColBarBefore: function (key, row) {
                    return true;
                },
                onClickColBtn: function (context, btn, row) {
                    switch (btn.key) {
                        case "edit":
                            whenEdit(context, btn.href, row.id);
                            break;
                        case "view":
                            whenView(context, row);
                            break;
                        case "security":
                            whenSetSecurity(context, btn.href, row);
                            break;
                        case "role":
                            whenSetRole(context, btn.href, row);
                            break;
                        case "department":
                            whenSetDepartment(context, btn.href, row);
                            break;
                        default :
                            break;
                    }
                },
                onClickToolbarBtn: function (context, btn) {
                    switch (btn.key) {
                        case "search_all":
                            context.searchAll();
                            break;
                        case "search":
                            context.search(btn.href, "用户搜索", "user_search");
                            break;
                        case "add":
                            whenAdd(context, btn.href);
                            break;
                        case "upload":
                            whenUpload(context);
                            break;
                        case "del":
                            context.del(btn.href);
                            break;
                        default :
                            break;
                    }
                }
            }
        });
        var contextWindow = new $.PageWindow();

        function whenEdit(context, href, id) {
            contextWindow.create({
                href: href + "?id=" + id,
                method: "user_edit_save",
                title: "编辑用户",
                callback: function (status) {
                    if (status) {
                        context.grid.datagrid("reload");
                    }
                }
            });
            contextWindow.open();
        }

        function whenView(context, row) {
            context.detail("用户详情", row);
        }

        function whenAdd(context, href) {
            contextWindow.create({
                href: href,
                method: "user_add_save",
                title: "新增用户",
                callback: function (status) {
                    if (status) {
                        context.grid.datagrid("reload");
                    }
                }
            });
            context.grid.datagrid('clearSelections');
            contextWindow.open();
        }

//        function whenUpload(context) {
//            $.DataImportPanel.getPanel("user_data_import", {
//                server: "${ctx}"
//            }).open();
//        }

        function whenSetSecurity(context, href, row) {
            contextWindow.create({
                href: href + "?id=" + row.id,
                method: "resource_save",
                title: "分配(" + row.userName + ")权限",
                callback: function (status) {
                    if (status) {
                        context.grid.datagrid("reload");
                    }
                }
            });
            contextWindow.open();
        }

        function whenSetRole(context, href, row) {
            contextWindow.create({
                href: href + "?id=" + row.id,
                method: "role_save",
                title: "分配(" + row.userName + ")角色",
                callback: function (status) {
                    if (status) {
                        context.grid.datagrid("reload");
                    }
                }
            });
            contextWindow.open();
        }

        function whenSetDepartment(context, href, row) {
            contextWindow.create({
                href: href + "?id=" + row.id,
                method: "organization_save",
                title: "分配(" + row.userName + ")小组",
                callback: function (status) {
                    if (status) {
                        context.grid.datagrid("reload");
                    }
                },
                width: 400,
                height: 325
            });
            contextWindow.open();
        }

        return {
            pageFactory:_pageComponent
        }
    };

    function modify(ctx, page){
        page.getJqDom("userHeadList").combobox({
            url: ctx + "/app/api/file/userHeadList",
            valueField: 'id',
            textField: 'text',
            onLoadSuccess: function(){
                page.getJqDom("userHeadTd").find(".textbox-text").css({"display":"none"});
                page.getJqDom("userHeadTd").find(".textbox-icon").css({"width":"400px"});
                $(".combobox-item").css({"padding":"5px","display":"inline-block"});
            },
            onSelect: function(record){
                page.getJqDom('userHead').attr("src", ctx + "/print" + record.id);
            }
        });

        page.getJqDom('uploadCover').cropImageUpload({
            onCropComplete:function(event, ins){
                var file = ins.file;
                page.getJqDom('uploadCover').val(file);
                page.getJqDom('userHead').attr("src", ctx + "/print" + file);
            }
        });
        page.getJqDom("available").toggleButton({
            dataRef:{
                "0":"禁用",
                "1":"启用"
            }
        });
        page.getJqDom("ipAddress").tagEditor({
            delimiter: ',',
            clickDelete: true,
            placeholder: 'IP地址..'
        });
    }

    exports.update = function(ctx, uuid){
        var page = new $.PageDomFactory(uuid);
        modify(ctx, page);
        window.user_edit_save = function(win){
            var postForm = page.getJqDom("form-user-update-info");
            if (!postForm.form('validate')) {
                return false;
            }
            win.wait("start", "保存中,请稍候.");
            var postData = postForm.serializeJson();
            $.post(postForm.attr(
                    "action")
                    + "?random=" + Math.random(), $.utils.buildJson(postData),
                function (json) {
                    win.wait("end");
                    if ($.isPlainObject(json) && json.error) {
                        $.messager.alert('信息',
                            json.msg, 'info');
                    } else {
                        $.messager.alert('信息',
                            '保存成功', 'info');
                        win.callback(true);
                        win.close();
                    }
                }, "json");
        }
    };

    require("apps/tag");
    exports.add = function(ctx, uuid){
        var page = new $.PageDomFactory(uuid);
        modify(ctx, page);
        page.getJqDom("user_salt").val(Math.random() * 1000000000000000000);
        window.user_add_save = function(win) {
            var postForm = page.getJqDom("form-user-add-info");
            if (!postForm.form('validate')) {
                return false;
            }
            win.wait("start", "保存中,请稍候.");
            var postData = postForm.serializeJson();
            $.post(postForm.attr("action") + "?random=" + Math.random(), $.utils.buildJson(postData),
                function (json) {
                    win.wait("end");
                    if ($.isPlainObject(json) && json.error) {
                        $.messager.alert('信息',
                            json.msg, 'info');
                    } else {
                        $.messager.alert('信息',
                            '保存成功', 'info');
                        win.callback(true);
                        win.close();
                    }
                }, "json");
        }

        return {
            pageFactory:page
        }
    }

    exports.search = function(ctx, uuid){
        var page = new $.PageDomFactory(uuid);
        page.getJqDom("available").combobox({
            editable: false
        });

        window.user_search = function(win){
            win.wait("start", "搜索中,请稍候.");
            var form = page.getJqDom("form-search-info");
            var postData = form.serializeJson();
            win.callback(postData);
            win.close();
        }
    }

    exports.organization = function(ctx, uuid, config){
        var page = new $.PageDomFactory(uuid);
//        page.getJqDom("organizations").tree({
//            url: ctx + "/app/api/organization/showOrganizations?userId=" + config.userId,
//            checkbox: true
//        });
        page.getJqDom("organizations").find("input:checkbox").click(function(){
            if($(this).prop("checked")){
                $(this).parent().siblings().children().prop("checked", false);
            }
        });

        window.organization_save = function(win){
            win.wait("start","保存中,请稍候.");
//            var nodes = page.getJqDom("organizations").tree("getChecked");
//            var ids = nodes.map(function (item) {
//                return item.id;
//            });
            var ids = [];
            page.getJqDom("organizations").find("input:checked").each(function(){
                ids.push($(this).attr("data-id"));
            });
            $.post(ctx + "/app/api/sysMember/saveUserOrganization",
                $.utils.buildJson({'ids': ids, userId: config.userId}), function (json) {
                    win.wait("end");
                    $.messager.alert('信息', '保存成功!', 'info');
                    win.callback(true);
                    win.close();
                }, 'json');
        }
    }

    exports.role = function(ctx, uuid, config){
        var page = new $.PageDomFactory(uuid);
        page.getJqDom("member_role_userId").mutiSelect({
            url:ctx + "/app/api/role/list",
            params:{userId:config.userId},
            idFiled:"id",
            textFiled:"roleName"
        });

        window.role_save = function(win){
            win.wait("start", "保存中,请稍候.");
            var postData = page.getJqDom("postForm").serializeJson();
            $.post(ctx + "/app/api/sysMember/saveUserRole", $.utils.buildJson(postData), function (json) {
                win.wait("end");
                $.messager.alert('信息', '保存成功!', 'info');
                win.close();
            }, 'json');
        }
    }
});